package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.mq.listener.vo.IotMsgNotifyData;
import com.zzyl.nursing.mq.listener.vo.IotMsgService;
import com.zzyl.nursing.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-06
 */
@Slf4j
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;

    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //1. 通过设备id查询设备
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceService.lambdaQuery()
                .eq(Device::getIotId, iotId)
                .one();

        //如果不存在，直接结束
        if (device == null) {
            log.warn("设备不存在：{}");
            return;
        }

        //2. 构建设备数据（循环添加,先循环services，再循环物模型，map）
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();
        if (CollUtil.isEmpty(services)) {
            log.warn("设备数据为空：{}", iotId);
            return;
        }
        List<DeviceData> deviceDataList = new ArrayList<>();
        //先遍历services服务
        services.forEach(ims -> {
            //处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(ims.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //获取上报数据
            Map<String, Object> properties = ims.getProperties();
            //遍历上报的物模型
            properties.forEach((k, v) -> {
                //封装数据到DeviceData
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setId(null);
                deviceData.setFunctionId(k);
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setDataValue(v.toString());
                deviceData.setAlarmTime(alarmTime);
                deviceDataList.add(deviceData);
            });
        });

        //3.批量保存
        saveBatch(deviceDataList);
    }

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }
}
